<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    let event = {
      list: {},
      // 发布：要将触发的事件声明，然后等待订阅
      listen: function (key, fn) {
        (this.list[key] || (this.list[key] = [])).push(fn)
      },
      trigger: function () {
        let key = Array.prototype.shift.call(arguments),
            fns = this.list[key]
        // key: 是传入的那个方法
        // console.log('fns', fns, this.list, key);
        if (!fns || fns.length === 0) {
          return
        }
        for (let index = 0, fn; fn=fns[index++];) {
          console.log('fn', fn);
          // 发布消息时的参数
          fn.apply(this, arguments)
        }
      }
    }
    let initEvent = function (obj) {
      for (let i in event) {
        obj[i] = event[i]
      }
    }

    let houseObj = {}
    initEvent(houseObj)
    houseObj.listen('big', function(size) {
      console.log('小红：我要的房子是' + size + '平方');
    })
    houseObj.listen('small', function(size) {
      console.log('小绿：我要的房子是' + size + '平方');
    })
    houseObj.trigger('big', 150)
    houseObj.trigger('big', 180)
    houseObj.trigger('small', 80)
  </script>
</html>
